import cv2
import numpy as np

# 读取图像
img1 = cv2.imread('image1.jpg')  # 第一张图
img2 = cv2.imread('draw_3.jpg')  # 第二张图

# 获取图像的尺寸
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]

# 计算图像的比例
ratio1 = w1 / h1
ratio2 = w2 / h2

# 定义目标尺寸
target_width = w1
target_height = h1

print("w1,h1,w2,h2", w1,h1,w2,h2)
print("ratio1, ratio2", ratio1, ratio2)

# 判断比例是否相同
if np.isclose(ratio1, ratio2):
    # 如果比例相同，直接缩放为第一张图的大小
    resized_img2 = cv2.resize(img2, (target_width, target_height))
else:
    if ratio1 > ratio2:
        # 扩展宽度
        max_h = max(h1, h2)
        max_w = int(w1 * max_h / h1)
        # resized_img2 = cv2.resize(img2, (max_w, max_h))
        left = (max_w - w2) // 2
        right = left
        print("max_w, max_h", max_w, max_h)
        print("left, right",left, right)
        resized_img2 = cv2.copyMakeBorder(img2, 0, 0, left, right, cv2.BORDER_CONSTANT, value=(0, 0, 0))
       
    else:
        # 扩展高度
        max_w = max(w1, w2)
        max_h = int(h1 * max_w / w1)
        # resized_img2 = cv2.resize(img2, (max_w, max_h))
        top = (max_h - h2) // 2
        bottom = top
        print("max_w, max_h", max_w, max_h)
        print("top, bottom",top, bottom)
        resized_img2 = cv2.copyMakeBorder(img2, top, bottom, 0, 0, cv2.BORDER_CONSTANT, value=(0, 0, 0))
    # 最后缩放到目标尺寸
    resized_img2 = cv2.resize(resized_img2, (target_width, target_height))

# 保存结果
cv2.imwrite('resized_image2.jpg', resized_img2)

# 显示结果
# cv2.imshow('Image 1', img1)
# cv2.imshow('Resized Image 2', resized_img2)

# 等待按键按下
# cv2.waitKey(0)
# cv2.destroyAllWindows()